<template>
  <div class="echartcalender" id='mycalender' v-loading="loadingMask">
  </div>
</template>

<script>
// 导入网络请求
import { getLocations } from '../../../network/showManage'
import { getcurrentmonthshowdata } from '../../../network/home'
// vuex
import { mapActions } from 'vuex'
export default {
  name: 'calender',
  data () {
    return {
      // 保存charts实例
      mycalender_charts: null,
      // 当前年
      cyear: 0,
      // 当前月
      cmon: 0,
      // 当前日期
      cday: 0,
      // 当前年月日期
      currentYear: '',
      // 当前日期
      thisDay: '',
      // 月份大写
      month: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
      // 当前日历数据
      calendardata: [],
      // 当前月的演出数据
      calendershow: [],
      // echarts数据
      echartsdata1: [],
      echartsdata2: [],
      // echarts日历表格中每个单元格的大小
      cellSize: [60, 60],
      // 设置每个剧院的标识符
      mark: [],
      marklen: 0,
      markname: [],
      // mark需要偏移的量
      markoffset: [],
      // mark的颜色
      markColor: ['#409EFF', '#c23531', '#2f4554', '#61a0a8'],
      // 日历区加载mask
      loadingMask: false
    }
  },
  methods: {
    ...mapActions(['getmonthshowdata']),
    // 通过getlocation网络请求获取到所有的剧院，然后处理出说有剧院的大写首字母
    getalltheater () {
      // this.$axios.get('http://localhost:3033/getlocation')
      getLocations().then(res => {
        // console.log(res.data.location)
        res.data.location.forEach(item => {
          this.mark.push(item.value)
          this.markname.push(item.label)
        })
        this.marklen = this.mark.length
        // console.log(this.marklen)
      })
    },
    // echarts函数
    getmycalender () {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.mycalender_charts = this.$echarts.init(document.getElementById('mycalender'))
      // 这里要存下this的指向，之后的配置中会出现指向问题
      let that = this
      let len = this.mark.length
      // 多个剧目渲染参数
      let scatterData = []
      // 这里放响应式的数据
      let layoutData = [];
      (function () {
        for (let idx = 0; idx < len; idx++) {
          // console.log('111')
          // 用来保存偏移位数
          let rowData = {
            type: 'effectScatter',
            name: `${that.markname[idx]}`,
            coordinateSystem: 'calendar',
            symbolSize: 1,
            data: that.echartsdata2,
            tooltip: {
              show: false
            },
            emphasis: {
              itemStyle: {
                opacity: 0,
                borderColor: 'rgba(0, 0, 0, 0)'
              }
            },
            label: {
              show: true,
              formatter: function (params) {
                if (params.value[2].length > 0) {
                  let data = params.value[2]
                  let theatername = ''
                  data.forEach((s, index) => {
                    // 循环取出每个演出的theater名字，并且选取首字母
                    if (s.theater === that.mark[idx]) {
                      theatername = s.theater.substring(0, 1).toUpperCase()
                    }
                  })
                  return theatername
                } else {
                  return ''
                }
              },
              // offset用于设置文字偏移
              // offset: [-this.cellSize[0] / 2 + 12 + this.markoffset[idx], this.cellSize[1] / 2 - 12],
              // fontSize: 12,
              fontWeight: 600,
              color: that.markColor[idx + 1]
            }
          }
          scatterData.push(rowData)
        }
      }())
      function getlayout (size, fonts) {
        // console.log('处理布局信息')
        layoutData = [{
          symbolSize: size,
          label: {
            // offset用于设置文字左上角偏移
            offset: [-size / 2 + fonts, -size / 2 + fonts],
            fontSize: fonts
          }
        }]
        // 每次偏移量
        let onceoffset = size / that.mark.length
        for (let idx = 0; idx < that.mark.length; idx++) {
          let d = idx * onceoffset
          let data = {
            label: {
            // 目前我们只要更改
            // offset用于设置文字偏移
              offset: [-size / 2 + fonts + d, size / 2 - fonts],
              fontSize: fonts
            }
          }
          layoutData.push(data)
        }
        return layoutData
      }
      // 指定图表的配置项和数据
      let option = {
        baseOption: {
          // 标题配置
          title: {
            show: true,
            text: `${this.month[this.cmon - 1]}月演出信息`,
            width: '100%',
            textStyle: {
              fontSize: '30'
            },
            textAlign: 'left'
          },
          // 弹框显示的信息配置
          tooltip: {
            show: true,
            confine: true,
            formatter: p => {
              if (p.value[2].length > 0) {
                let tooltipShowdata = p.value[2]
                let color = this.markColor
                let currentday = `${p.value[0]}<br/>`
                // console.log(showdata)
                let currentshow = ``
                for (let i = 0; i < tooltipShowdata.length; i++) {
                  let idx = this.mark.findIndex(s => { return s === tooltipShowdata[i].theater })
                  let showdata = `<div class="tooltext">
                      《${tooltipShowdata[i].showName}》
                      <span style="background-color: ${color[idx + 1]}; padding: 0 5px">${tooltipShowdata[i].theaterName}/${tooltipShowdata[i].hall}</span>
                      演出类型: ${tooltipShowdata[i].type}
                      </div>`
                  currentshow = currentshow + showdata
                }
                return currentday + currentshow
              }
            }
          },
          // 预设颜色
          color: this.markColor,
          // 侧边图例
          legend: {
            data: this.markname.map((d, idx) => ({
              name: d
            }))
          },
          // 日历配置
          calendar: {
            yearLabel: { show: false },
            orient: 'vertical',
            dayLabel: {
              firstDay: 1,
              nameMap: 'cn'
            },
            monthLabel: { show: false },
            range: this.currentYear
          },
          // 数据展示
          series: [
            {
              // 第一组数据用于显示日期
              type: 'scatter',
              coordinateSystem: 'calendar',
              hoverAnimation: false,
              data: this.echartsdata2,
              label: {
                show: true,
                formatter: function (params) {
                  let d = new Date(params.value[0])
                  return d.getDate()
                },
                // offset用于设置文字左上角偏移
                // offset: [-this.cellSize[0] / 2 + 12, -this.cellSize[1] / 2 + 12],
                // fontSize: 12,
                fontWeight: 700,
                color: '#000'
              }
            },
            // es6语法把scatterdata中的数据取出来
            ...scatterData

          ]
        },
        media: [
          {
            option: {
              legend: {
                orient: 'vritical',
                itemHeight: 24,
                itemWidth: 24,
                left: 5,
                bottom: 64
              },
              calendar: {
                right: 8,
                top: 'center',
                cellSize: this.cellSize
              },
              series: [
                ...getlayout(60, 12)
              ]
            }
          },
          {
            query: {
              maxWidth: 545
            },
            option: {
              legend: {
                orient: 'horizontal',
                itemHeight: 24,
                itemWidth: 24,
                left: 'center',
                bottom: 40
              },
              calendar: {
                right: 8,
                top: 'center',
                cellSize: [60]
              },
              series: [
                ...getlayout(60, 12)
              ]
            }
          },
          {
            query: {
              maxWidth: 436
            },
            option: {
              legend: {
                orient: 'horizontal',
                itemHeight: 24,
                itemWidth: 24,
                left: 5,
                bottom: 'bottom'
              },
              calendar: {
                right: 8,
                top: 'center',
                cellSize: [50]
              },
              series: [
                ...getlayout(45, 10)
              ]
            }
          }
        ]
      }
      // 显示加载动画
      // myChart.showLoading('default')
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option, {
        lazyUpdate: true
      })
    },
    // 通过网络请求当前月的所有演出
    getMonthData () {
      getcurrentmonthshowdata(this.cmon).then(res => {
        if (res.status === 200) {
          let data = res.data.showData
          this.getmonthshowdata(data)
          // 这里在前端处理的数据交给后端处理了
          // 删除数据，只保留日期/剧目名/演出地点信息
          for (let i = 0; i < data.length; i++) {
            data[i].show.forEach(item => {
              this.calendershow.push(item)
            })
          }
          this.chartdata()
          this.getmycalender()
        }
      })
    },
    // 处理echarts函数数据
    chartdata () {
      for (let i = 0; i < this.calendardata.length; i++) {
        let day = this.calendardata[i]
        let show = this.calendershow.filter(item => {
          return item.date === day
        })
        // 每个子数组分别是时间、今天有几场演出、每个演出详细信息
        this.echartsdata1.push([
          day,
          show.length,
          show
        ])
        this.echartsdata2.push({
          value: [day, show.length, show],
          // 为当前日期标注颜色
          itemStyle: this.calendardata[i] === this.thisDay ? { color: '#409EFF', opacity: '0.5' } : { color: '#fff' },
          // 长方形来填充
          symbol: 'rect'
        })
      }
    },
    // 获取当前月日期数据
    getCurrentData () {
      let now = new Date()
      // 获取当前年月
      this.cyear = now.getFullYear()
      this.cmon = now.getMonth() + 1
      this.cday = now.getDate()
      // 设置当前年月信息
      this.currentYear = `${this.cyear}-${this.padLeftZero(this.cmon + '')}`
      // 设置当前日期
      this.thisDay = `${this.cyear}-${this.padLeftZero(this.cmon + '')}-${this.padLeftZero(this.cday + '')}`
      // 判断是否是闰年
      let isleap = this.is_leap(2020)
      // 记录下当前月是否是大月
      let ismonth = [1, 3, 5, 7, 8, 10, 12].includes(this.cmon)
      // 判断当前月有多少天
      let monday
      if (this.cmon === 2) {
        if (isleap) {
          monday = 29
        } else {
          monday = 28
        }
      } else if (this.cmon !== 2 && ismonth) {
        monday = 31
      } else {
        monday = 30
      }
      // console.log(this.cyear, this.cmon, monday)
      // 循环生成这个月的日历数组
      for (let i = 1; i <= monday; i++) {
        let mon = this.padLeftZero(this.cmon + '')
        let day = this.padLeftZero(i + '')
        this.calendardata.push(`${this.cyear}-${mon}-${day}`)
      }
    },
    // 判断是否为闰年
    is_leap (year) {
      let leap = year % 100 === 0 ? (year % 400 === 0 ? 1 : 0) : (year % 4 === 0 ? 1 : 0)
      return leap
    },
    // 补0函数
    padLeftZero (str) {
      return ('00' + str).substr(str.length)
    }
  },
  created () {
    this.getalltheater()
    this.getCurrentData()
  },
  mounted () {
    window.onresize = () => {
      this.mycalender_charts.resize()
    }
    // if (this.$store.state.monthshowdata.length) {
    //   // 重置当前月的演出数据
    //   this.calendershow = []
    //   // 重置echarts数据
    //   this.echartsdata1 = []
    //   this.echartsdata2 = []
    //   this.$nextTick(() => {
    //     console.log(this.$store.state.monthshowdata)
    //     console.log('数据已经保存')
    //     let data = this.$store.state.monthshowdata
    //     for (let i = 0; i < data.length; i++) {
    //       data[i].show.forEach(item => {
    //         this.calendershow.push(item)
    //       })
    //     }
    //     this.chartdata()
    //     this.getmycalender()
    //   })
    // } else {
    this.getMonthData()
    // }
  }
}
</script>

<style lang="stylus" scoped>
.echartcalender
  width 100%
  height 100%
</style>
